<?php
//ob_start();

if(isset($_SERVER['HTTP_ORIGIN'])) {
    header('Access-Control-Allow-Origin:'.$_SERVER['HTTP_ORIGIN']);
    header('Access-Control-Max-Age: 3600');
    header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE');
    header('Access-Control-Allow-Headers:Content-Type');
    header('Access-Control-Allow-Credentials: true');
}

if(!empty($_POST['auth'])) {
    $_COOKIE['9I6A_2132_auth'] = base64_decode($_POST['auth']);
    $_COOKIE['9I6A_2132_saltkey'] = $_POST['saltkey'];
    //print_r($_COOKIE);exit;
}

//if($_SERVER['REMOTE_ADDR'] != 'you ip') {
//    header('Content-Type:text/html;charset=utf-8');
//    exit('网站正在升级中，请不要访问，谢谢！');
//}
error_reporting(0);
//error_reporting(E_ALL);
if(!defined('FANWE_ROOT'))
	define('FANWE_ROOT', str_replace('core/fanwe.php', '', str_replace('\\', '/', __FILE__)));

if(!include_once(FANWE_ROOT.'./core/function/global.func.php'))
	exit('not found global.func.php');

include_once fimport("function/time");
include_once(FANWE_ROOT.'./core/function/mfkit.func.php');
require FANWE_ROOT.'core/service/think.service.php';

class FanweService
{
	public $db = NULL;
	public $cache = NULL;
	public $session = NULL;
	public $memory = NULL;
	public $is_init = false;
	public $is_memory = true;
	public $is_session = true;
	public $is_admin = false;
	public $is_user = true;
	public $is_cron = true;
	public $is_setting = true;
	public $is_misc = true;
	public $config = array();
	public $var = array();
	public $cache_list = array('user_group','goods_category','image_servers','business','links','navs','seos');

	public $allow_global = array(
		'GLOBALS' => 1,
		'_GET' => 1,
		'_POST' => 1,
		'_REQUEST' => 1,
		'_COOKIE' => 1,
		'_SERVER' => 1,
		'_ENV' => 1,
		'_FILES' => 1,
		'_FANWE' => 1,
	);

	public function &instance()
	{
		static $_instance = NULL;
		if($_instance === NULL)
			$_instance = new FanweService();
		return $_instance;
	}

	public function FanweService()
	{
		initFanwe($this);
	}

	public function initialize()
	{
		global $_FANWE;
		initializeFanwe($this);
		if(isset($_FANWE['cache']['business']['taobao']) && $_FANWE['cache']['business']['taobao']['is_tdj'] == 0)
		{
			$app_key = $_FANWE['cache']['business']['taobao']['app_key'];
			$secret = $_FANWE['cache']['business']['taobao']['app_secret'];
			$timestamp = TIMESTAMP."000";
			$message = $secret.'app_key'.$app_key.'timestamp'.$timestamp.$secret;
			$mysign=strtoupper(hash_hmac("md5",$message,$secret));
			setcookie("timestamp",$timestamp);
			setcookie("sign",$mysign);
		}
		
		$this->_initWogu();
        $this->_initPos();
	}

    private function _initPos() {
        // 定位
        if(!isset($_SESSION['cityid']) && !empty($_GET['lat']) && is_numeric($_GET['lat'])) {
            $data = file_get_contents("http://apis.map.qq.com/ws/geocoder/v1/?location={$_GET['lat']},{$_GET['lng']}&key=6RSBZ-XTAH4-USGU3-DMDXO-WFZ7F-ENFER");
            if(!empty($data)) {
                $loc = json_decode($data, true);
                $city = str_replace('市', '', $loc['result']['address_component']['city']);
                $cities = include './public/city.php';
                foreach ($cities['all'] as $cityid => $v) {
                    if(false !== strpos($v['name'], $city) || false !== strpos($city, $v['name'])) {
                        $_SESSION['cityid'] = $cityid;
                        $_SESSION['cityname'] = $v['name'];
                    }
                }
            }
        }
    }
	
	private function _initWogu() {
	    global $_FANWE;
	    
	    if($_FANWE['uid'] > 0) {
	        if(!$_FANWE['user']['status']) {
	            exit('您的账号涉嫌违规已被限制登陆！');
	        }
	        
	        //商家信息
	        if($_FANWE['user']['user_type'] == 1) {
                $sql = 'SELECT * FROM '.FDB::table('wogu_user_shop').' WHERE uid='.$_FANWE['uid'];
                $_FANWE['shop'] = FDB::fetchFirst($sql);
	        }
	        
	        //进度执行表
    	    $config = include FANWE_ROOT . 'public/plan.php';
    	    
            $sql = 'SELECT * FROM '.FDB::table('wogu_plan_items').' WHERE uid='.$_FANWE['uid'].' AND type=\'act\' AND flag=0 AND is_notice_comp=0';
            $res = FDB::query($sql);
            while($r = FDB::fetch($res)) {
                $items[] = $r;
                $listids[] = $r['list_id'];
            }
            
            if(empty($items)) return;
            $listids = array_unique($listids);
            $sql = 'SELECT id,ampm FROM '.FDB::table('wogu_plan_list').' WHERE id IN('.implode(',', $listids).')';
            $res = FDB::query($sql);
            while($r = FDB::fetch($res)) {
                $list[$r['id']] = $r;
            }

            foreach($items as $v) {
                $ampm = $list[$v['list_id']]['ampm'];
                $begin = $v['dateline'];
                $data = empty($v['data']) ? array() : unserialize($v['data']);
                $item = $v['pid'] == -1 ? $config[$v['myid']] : $config[$v['pid']]['children'][$v['myid']];
                foreach($item['items'][$ampm] as $k1 => $v1) {
                    if($k1 < $v['is_notice']) continue;

                    if(!isset($data[$k1])) {
                        if(strpos($v1['sj'], ':') !== false) {
                            $now = strtotime(date('Y-m-d'));
                            if($now == $v['dateline'] && strtotime(date('H:i:s')) >= strtotime($v1['sj'])) {
                                $this->_updatePlan($v1['tip'], $k1+1, $k1+1 == count($item['items'][$ampm]), $v['id']);
                                break;
                            }
                        } else {
                            if($begin - time() < $v1['sj'] * 86400) {
                                $this->_updatePlan($v1['tip'], $k1+1, $k1+1 == count($item['items'][$ampm]), $v['id']);
                                break;
                            }
                        }
                    }
                }
            }
	    }
	}
	
	private function _updatePlan($tip, $isnotice, $iscomp, $id) {
	    global $_FANWE;
	    
	    if(empty($tip))
	        $msg = "您的进度执行表中有一个项目快要过期，<a href=\"/list.php?action=plan&op=showitem&itemid={$id}\">赶紧处理</a>吧！";
	    else
    	    $msg = $tip."，<a href=\"/list.php?action=plan&op=showitem&itemid={$id}\">点击查看</a>！";
        FDB::query("INSERT INTO ".FDB::table("sys_notice")." (uid, title, content, create_time) VALUES({$_FANWE['uid']},'进度执行表通知','{$msg}','".time()."')");
        FS('User')->setUserTips($_FANWE['uid'], 6);
        
        $data = array('is_notice' => $isnotice);
        if($iscomp)
            $data['is_notice_comp'] = 1;
        FDB::update('wogu_plan_items', $data, array('id' => $id));
	}
}

?>